'use strict'
import {
  Model,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from 'sequelize'
import dayjs from 'dayjs'
import { Models } from '../type'
import sequelize from './index'

class Order extends Model<InferAttributes<Order>, InferCreationAttributes<Order>> {
  declare id: CreationOptional<number>
  declare outTradeNo: string
  /** 流水号 已支付/已取消才会有 */
  declare tradeNo: CreationOptional<string>
  /** 用户id */
  declare userId: number
  /** 角色id(权益信息) */
  declare roleId: number
  /** 订单备注信息(要买的商品名) */
  declare subject: string
  /** 金额 */
  declare totalAmount: number
  /** 支付方式 已支付/已取消才会有 */
  declare paymentMethod: CreationOptional<string>
  /** 订单状态 0: 未支付 1: 已支付 2: 已取消 */
  declare status: number
  /** 权益时长 */
  declare durationMonths: CreationOptional<number>
  /** 支付时间 已支付才会有 */
  declare paidAt: CreationOptional<Date>
  declare createdAt: CreationOptional<Date>
  declare updatedAt: CreationOptional<Date>

  static associate(models: Models) {
    Order.belongsTo(models.User, { as: 'user', foreignKey: 'userId' })
    // Order.belongsTo(models.Role, { as: 'role', foreignKey: 'roleId' })
  }
}
Order.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    outTradeNo: DataTypes.STRING,
    tradeNo: DataTypes.STRING,
    userId: DataTypes.INTEGER,
    roleId: DataTypes.INTEGER,
    subject: DataTypes.STRING,
    totalAmount: DataTypes.DECIMAL,
    paymentMethod: {
      type: DataTypes.ENUM,
      values: ['alipay', 'wxpay', 'qqpay', 'tenpay'],
    },
    status: DataTypes.TINYINT,
    durationMonths: {
      type: DataTypes.INTEGER,

      validate: {
        notEmpty: {
          msg: '权益时长不能为空。',
        },
        isInt: {
          msg: '权益时长必须为整数',
        },
        isPositive(value: number) {
          if (value <= 0) {
            throw new Error('角色时长必须是正整数。')
          }
        },
      },
    },
    paidAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('paidAt')
          ? dayjs(this.getDataValue('paidAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('createdAt')
          ? dayjs(this.getDataValue('createdAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('updatedAt')
          ? dayjs(this.getDataValue('updatedAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
  },
  {
    sequelize,
    modelName: 'Order',
  },
)

export default Order
